/**
 * 
 */
var _serverInit=0;
var _gameStatus1=-1;
var _lastHit = null;
var _soundEnabled = true;
var _idVar;
function getGameStatus()
{
	return _gameStatus1;
}
function pollStatus (){
	$.ajax({url: "./gameInstance", method: "GET",
	success: function(responseJson){
		if (_lastHit!=responseJson.lastHit)
		{
			_lastHit=responseJson.lastHit;
			paintSingleCell(_lastHit,"red");
			//hitStatus : 0 - miss, 1 - hit, 2- drowned
			var hitStatus = responseJson.hitStatus;
			if (hitStatus == 0 && _soundEnabled)
			{
				splashSound();
			}
			else if (hitStatus == 1 && _soundEnabled)
			{
				explosionSound();
			}
			else if (hitStatus ==3 && _soundEnabled)
			{
				SOSSound();
			}
			addShotsToStorage(1,_lastHit,hitStatus,null);
			
		}
		if (_gameStatus1!=parseInt(responseJson.gameStatus))
		{
			_gameStatus1=parseInt(responseJson.gameStatus);
			if (_gameStatus1==0)
			{
				$('#messageBox').html("<p id='message'>Paiguta<p>");
			}
			else if (_gameStatus1==1)
			{
				$('#messageBox').html("<p id='message'>Tuld!<p>");
			}
			else if (_gameStatus1==2)
			{
				$('#messageBox').html("<p id='message'>Varju!<p>");
			}
			else if (_gameStatus1==3)
			{
				$('#messageBox').html("<p id='message'>Voit!!<p>");
				putGameLocalStorage();
				$.post("./game",{Status:"0",GameID:String(_idVar)});
			}
			else if (_gameStatus1==4)
			{
				$('#messageBox').html("<p id='message'>Kaotus!!<p>");
				putGameLocalStorage();
			}
		}
	}, dataType:"json",complete: pollStatus, timeout:30000 });
}
function initServer ()
{
	_idVar = parseInt((window.location.href).split("=")[1]);
	$.post("./gameInstance",{id:String(_idVar),status:String(0)},function()
			{
				_serverInit=1;
				pollStatus();
			});
}
function deployToServer(ships,cells,conf,shipLoc)
{
	//Confirm 1 - deploy, 0 - cancelLastDeploy
	$.post("./gameInstance",{status:String(1),confirm:String(conf),ships:(JSON.stringify(ships)),cells:(JSON.stringify(cells)),shipLocs:(JSON.stringify(shipLoc))});
	//to local storage
	addMyShipPlacement(JSON.stringify(shipLoc));
}
function cellToServer(cellArg)
{
	$.ajax({type:"POST",url:"./gameInstance", data: {status:String(2),cell:String(StoInt(cellArg))},dataType:"text", success: function(responseJson)
			{
				var json = JSON.parse(responseJson);
				var cellSplit = cellArg.split(",");
				var cellJQuery= "#"+cellSplit[0]+"\\,"+cellSplit[1];
				if (json.hit == "true")
					{
					$(cellJQuery).css('background-color','orange');
					if (json.drown!=null)
					{
						var bordering = shipBorders(json.drown,null);
						opacityOpponentCells(shipBorders(json.drown,null),"0.4");
						paintOpponent(json.drown,"red");
					}
					}
				else
					{
					$(cellJQuery).css('background-color','blue');
					}
				addShotsToStorage(0,cellJQuery,json.hit,json.drown);
			}});
}
function surrender()
{
	$.post("./gameInstance",{status:String(3)});
}
